package com.dlc.shop.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.model.User;
import com.dlc.shop.common.enums.SysTypeEnum;
import com.dlc.shop.security.common.bo.UidInfoBO;
import com.dlc.shop.security.common.manager.TokenStore;
import com.dlc.shop.security.common.vo.TokenInfoVO;
import com.dlc.shop.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/wxsmLogin")
@AllArgsConstructor
@Slf4j
public class WxSmLoginController {

    private final UserService userService;
    private final TokenStore tokenStore;

    @GetMapping("/callback")
    public Map<String,String> callback(String code, String state) throws Exception {
        // 获取code值，拿着 code 请求微信固定地址，得到 accsess_token 和 openId
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                "wx07a6f060dc740cee",
                "0626e94c43cef1a7d2e71ff0cd3c6d98",
                code);
        String result = new RestTemplate().getForObject(accessTokenUrl,String.class);
        HashMap<String,String> hashMap = JSON.parseObject(result, HashMap.class);
        String accessToken =  hashMap.get("access_token");
        String openid =  hashMap.get("openid");
        log.info("token：{}，openid：{}",accessToken,openid);

        // 查询数据库当前用用户是否曾经使用过微信登录
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                                .eq(User::getWxOpenId, openid));
        Map<String,String> map=new HashMap<>();
        if (user == null){
            //拿着openid 和 access_token 请求微信地址，得到扫码人信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String resultInfo = new RestTemplate().getForObject(userInfoUrl,String.class);
            JSONObject resultUserInfo = JSONObject.parseObject(resultInfo);
            //获取昵称
            String nickname = resultUserInfo.getString("nickname");
            //获取头像
            String headimgurl = resultUserInfo.getString("headimgurl");

            map.put("code","0");
            map.put("openid",openid);
            map.put("nickname",nickname);
            map.put("headimgurl",headimgurl);
        }else {
            map.put("code","1");
            TokenInfoVO tokenInfoVO = tokenStore.storeAndGetVo(new UidInfoBO(SysTypeEnum.ORDINARY, user.getUserId()));
            map.put("accessToken",tokenInfoVO.getAccessToken());
        }
        return map;
    }


}
